const { DataTypes } = require('sequelize');
const { sequelize } = require('../config/database');

const Category = sequelize.define('Category', {
  id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true
  },
  name: {
    type: DataTypes.STRING(50),
    allowNull: false,
    unique: true
  },
  parentId: {
    type: DataTypes.INTEGER,
    allowNull: true,
    references: {
      model: 'categories',
      key: 'id'
    },
    field: 'parent_id' // 明确指定数据库列名
  },
  description: {
    type: DataTypes.STRING(200),
    allowNull: true
  },
  icon: {
    type: DataTypes.STRING(50),
    allowNull: true
  },
  sort: {
    type: DataTypes.INTEGER,
    defaultValue: 0,
    allowNull: false
  },
  isActive: {
    type: DataTypes.BOOLEAN,
    defaultValue: true,
    allowNull: false,
    field: 'is_active' // 明确指定数据库列名
  }
}, {
  tableName: 'categories',
  indexes: [
    {
      fields: ['parent_id'], // 使用数据库列名
      name: 'categories_parent_id' // 明确指定索引名称
    },
    {
      fields: ['sort'],
      name: 'categories_sort' // 明确指定索引名称
    }
  ]
});

// 获取分类树
Category.getTree = async function() {
  const categories = await this.findAll({
    order: [['sort', 'ASC']]
  });

  const buildTree = (items, parentId = null) => {
    const result = [];
    for (const item of items) {
      if (item.parentId === parentId) {
        const children = buildTree(items, item.id);
        if (children.length) {
          item.children = children;
        }
        result.push(item);
      }
    }
    return result;
  };

  return buildTree(categories);
};

// 获取分类及其所有子分类的ID
Category.getDescendantIds = async function(categoryId) {
  const result = new Set([categoryId]);
  const categories = await this.findAll();
  
  const findChildren = (parentId) => {
    for (const category of categories) {
      if (category.parentId === parentId) {
        result.add(category.id);
        findChildren(category.id);
      }
    }
  };

  findChildren(categoryId);
  return Array.from(result);
};

module.exports = Category;